// pages/wiki/[slug].js
import { useRouter } from 'next/router';
import { GetStaticPaths, GetStaticProps } from 'next';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import MDXLayout from '../components/MDXLayout';
import MarkdownIt from 'markdown-it';
import BlogForceGraph from '../components/BlogForceGraph';
import { Kbd } from 'flowbite-react';
import Link from 'next/link';
import { Card } from 'flowbite-react';
import '@/pages/blogs/markdown.css';
import { plantuml } from '@mdit/plugin-plantuml';
import { motion } from "motion/react"
import { useScroll } from 'motion/react';
// import { myPlugin } from '../components/DoubleLink'; 
// 创建一个 MarkdownIt 实例
const md = new MarkdownIt({html:true});
md.use(plantuml);

// 自定义插件
function customLinkPlugin(md, options) {
  // 定义一个新的规则来匹配 [[link]] 语法
  md.inline.ruler.push('custom_link', (state, silent) => {
      if (silent) return false;

      // 正则表达式匹配 [[link]]
      const re = /\[\[([^\]]+)\]\]/;
      const match = state.src.match(re);

      if (!match) return false;

      // 获取匹配的文本
      const linkText = match[1];

      // 创建一个新的 token
      const token = state.push('link_open', 'a', 1);
      token.attrSet('href', "/blogs/"+linkText); // 这里简单地将链接文本作为 href，你可以根据需要修改
      token.markup = '[[';

      // 添加链接文本 token
      state.push('text', '', 0).content = linkText;

      // 关闭链接 token
      state.push('link_close', 'a', -1);

      // 跳过已匹配的文本长度
      state.pos += match[0].length;

      return true;
  });
}
md.use(customLinkPlugin);

// md.use(myPlugin);
const BLOG_DIR = process.env.BLOG_DIR

async function loadBlogData() {
  try {

    const filePath = path.join(BLOG_DIR, ".zettelkasten")

    const data = fs.readFileSync(filePath, 'utf8');

    return JSON.parse(data);


  } catch (err) {
    console.error(`Error reading directory ${BLOG_DIR}:`, err);
  }
}


export const getStaticPaths = async () => {
  const blogData = await loadBlogData();
  const paths = blogData.map((blog) => ({
    params: { slug: [blog.path] },
  }))
  return { paths, fallback: false };
};

function transformGraphNode(datas, includeNodes, node) {


  const nodes = datas.filter((it) => includeNodes.indexOf(it.id) != -1);
  const links = [];
  for (var it in node.links) {
    links.push({
      "source": node.id,
      "target": node.links[it]
    })
  }
  return {
    nodes: nodes,
    links, links
  }
}

export const getStaticProps = async ({ params }) => {
  const { slug } = params;
  const fileName = slug.pop();
  const blogData = await loadBlogData();
  blogData.forEach(item => {
    item.id = item.path;
    item.label = item.filePath.split("\\").pop().split(".md")[0];
    item.group = item.category.join(",");
  })

  const nowBlog = blogData.find(blog => blog.path == fileName);
  
  if(nowBlog==null){
    nowBlog = blogData.find(blog => blog.filePath.split("\\").pop().split(".md")[0] == fileName )
  }
  const links = nowBlog.links;
  links.push(nowBlog.id);
  //反向关联
  blogData.filter((it)=>it.links.indexOf(nowBlog.id)>-1).forEach((it)=>links.push(it.path));
  const graphNode = transformGraphNode(blogData, links, nowBlog);


 
  const fullPath =  path.join(path.join(BLOG_DIR, "build"),nowBlog.path+".md");
  const fileContents = fs.readFileSync(fullPath, 'utf8');
  const { data, content } = matter(fileContents);
  // 使用 markdown-it 将 Markdown 内容转换为 HTML
  const htmlContent = md.render(content);

  return {
    props: {
      source: htmlContent,
      frontMatter: data,
      graphNode: graphNode
    },
  };
};
const MDXPage = ({ source, frontMatter, graphNode }) => {
  const { scrollYProgress } = useScroll()
  return (
    <MDXLayout>
      <div className="flex w-full h-full justify-center bg-white p-10">

        <div className='flex w-1/4 flex-col p-10'>

          <h2>相关阅读</h2>
          <div className='grid grid-cols-2 gap-2'>

            {
              graphNode.nodes.map((item) => (

                <Card className="max-w-sm" key={item.path}>
                  <div className="flex flex-wrap gap-2">
                    {

                      item.category.map(item => (
                        <Kbd key={item} >{item}</Kbd>
                      ))
                    }
                  </div>
                  <h5 className="text-xl font-bold tracking-tight text-gray-900 dark:text-white">
                    <Link key={item.path} href={"/blogs/" + item.path}>
                      {item.filePath.split("\\").pop().split(".md")[0]}
                    </Link>
                  </h5>

                </Card>
              ))
            }
          </div>

        </div>
        <div className='flex w-2/4 flex-col'>
          <h1>{frontMatter.title}</h1>
          <motion.div
                id="scroll-indicator"
                style={{
                  scaleX: scrollYProgress,
                  position: "fixed",
                  top: 0,
                  left: 0,
                  right: 0,
                  height: 10,
                  originX: 0,
                  backgroundColor: "#ff0088",
                }}
            />
          {/* <BlogForceGraph graphData={graphNode} showLabel={true} /> */}
          <div dangerouslySetInnerHTML={{ __html: source }} />


        </div>
        <div className='flex w-1/4 flex-col'>

        </div>
      </div>


    </MDXLayout>

  );
};

export default MDXPage;